package com.dushibao.view;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.dushibao.service.MenuService;
import com.dushibao.service.impl.MenuServiceImpl;
import com.dushibao.utils.AppUtils;
import com.dushibao.utils.CommUtils;
import com.dushibao.utils.SecurityHolder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class ModelAndView {
    MenuService menuService = new MenuServiceImpl();
    public ModelAndView(){}

    public ModelAndView(String viewName) throws ServletException, IOException {
        this(viewName,null);
    }
    //重构：在开发完成之后再去做这样的事 阿里巴巴Java开发手册 设计模式、代码规范、代码风格。。
    /**
     *
     * @param viewName 视图名称
     * @param attributes 请求参数
     * @throws ServletException
     * @throws IOException
     */
    public ModelAndView(String viewName, Map<String,Object> attributes) throws ServletException, IOException {
        HttpServletRequest request = SecurityHolder.request.get();
        HttpServletResponse response = SecurityHolder.response.get();

        request.setAttribute("colorAdmin", AppUtils.getValue("colorAdmin"));
        request.setAttribute("cdnServer",AppUtils.getValue("cdnServer"));
        request.setAttribute("menus",menuService.list());
        request.setAttribute("localDateTimeUtil", new LocalDateTimeUtil());
        request.setAttribute("commUtils",new CommUtils());

        if(attributes!=null) {
            for (String key : attributes.keySet()) {
                request.setAttribute(key, attributes.get(key));
            }
        }
        request.getRequestDispatcher("/WEB-INF/jsp/"+viewName+".jsp").forward(request,response);
    }
}
